package cn.iocoder.yudao.module.acm.dal.mysql.stock;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.acm.controller.admin.stock.vo.stock.AcmStockPageReqVO;
import cn.iocoder.yudao.module.acm.dal.dataobject.stock.AcmStockDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * Acm 产品库存 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface AcmStockMapper extends BaseMapperX<AcmStockDO> {

    default PageResult<AcmStockDO> selectPage(AcmStockPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<AcmStockDO>()
                .eqIfPresent(AcmStockDO::getProductId, reqVO.getProductId())
                .eqIfPresent(AcmStockDO::getWarehouseId, reqVO.getWarehouseId())
                .orderByDesc(AcmStockDO::getId));
    }

    default AcmStockDO selectByProductIdAndWarehouseId(Long productId, Long warehouseId) {
        return selectOne(AcmStockDO::getProductId, productId,
                AcmStockDO::getWarehouseId, warehouseId);
    }

    default int updateCountIncrement(Long id, BigDecimal count, boolean negativeEnable) {
        LambdaUpdateWrapper<AcmStockDO> updateWrapper = new LambdaUpdateWrapper<AcmStockDO>()
                .eq(AcmStockDO::getId, id);
        if (count.compareTo(BigDecimal.ZERO) > 0) {
            updateWrapper.setSql("count = count + " + count);
        } else if (count.compareTo(BigDecimal.ZERO) < 0) {
            if (!negativeEnable) {
                updateWrapper.ge(AcmStockDO::getCount, count.abs());
            }
            updateWrapper.setSql("count = count - " + count.abs());
        }
        return update(null, updateWrapper);
    }

    default BigDecimal selectSumByProductId(Long productId) {
        // SQL sum 查询
        List<Map<String, Object>> result = selectMaps(new QueryWrapper<AcmStockDO>()
                .select("SUM(count) AS sumCount")
                .eq("product_id", productId));
        // 获得数量
        if (CollUtil.isEmpty(result)) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(MapUtil.getDouble(result.get(0), "sumCount", 0D));
    }

}
